package com.huahai.security.core.authentication.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huahai.security.core.exception.TokenException;
import com.huahai.security.core.exception.ValidateCodeException;
import com.huahai.security.core.supports.ResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Jun
 * @Date: 2020/7/17
 *
 * 自定义用户登录认证失败处理器
 */
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private ResultResponse resultResponse = null;
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 认证失败后 执行此方法
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        if(resultResponse != null) {
            printWriter.write(objectMapper.writeValueAsString(resultResponse));
        } else{
            Map<String, String> map = new HashMap<>(2);
            map.put("status", "500");
            map.put("message", "认证信息有误，请重新登录");
            String resBody = objectMapper.writeValueAsString(map);
            printWriter.print(resBody);
        }
        printWriter.flush();
        printWriter.close();
    }

    /**
     * 为了 验证码验证失败后 能返回自定义信息 故添加此方法
     * @param request
     * @param response
     * @param e
     */
    public void doValidateCodeException(HttpServletRequest request, HttpServletResponse response, ValidateCodeException e){
        try {
            resultResponse = ResultResponse.build(e.getCode(),e.getMessage());
            this.onAuthenticationFailure(request, response, e);
        } catch (Exception ex) {
            logger.error("CustomAuthenticationFailureHandler#doValidateCodeException exception: {}", ex.getMessage());
        }
    }

    /**
     * 为了 token验证失败后 能返回自定义信息 故添加此方法
     * @param request
     * @param response
     * @param e
     */
    public void doTokenException(HttpServletRequest request, HttpServletResponse response, TokenException e){
        try {
            resultResponse = ResultResponse.build(e.getCode(),e.getMessage());
            this.onAuthenticationFailure(request, response, e);
        } catch (Exception ex) {
            logger.error("CustomAuthenticationFailureHandler#doTokenException exception: {}", ex.getMessage());
        }
    }
}
